<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/19
 * Time: 17:44
 */

namespace app\common\task\impl;


use app\common\task\AbstractCreditTask;
use think\Db;
use think\Exception;

class UserFollowTeacherTask extends AbstractCreditTask
{
    public function finished()
    {
        if (isset($this['maxTimes']) == false) {
            throw new Exception('Missing configuration "maxTimes"!');
        }

        $maxTimes = $this['maxTimes'];
        if (is_integer($maxTimes) == false) {
            throw new Exception('Configuration "maxTimes" type error, expect integer.');
        }

        $sql = <<<SQL
SELECT exists(
  SELECT 1 FROM user_follow_teacher_log WHERE userid=:uid AND teacher_id=:tid
) e
SQL;
        $re = Db::query($sql, ['uid'=>$this['uid'], 'tid'=>$this->params]);
        if ($re[0]['e']) return true;

        $sql = <<<SQL
SELECT count(*) c FROM user_follow_teacher_log WHERE userid=:uid AND created BETWEEN :ts AND :te
SQL;
        $start = date('Y-m-d');
        $end = date('Y-m-d', (strtotime($start) + 60 * 60 * 24));
        $re = Db::query($sql, ['uid'=>$this['uid'], 'ts'=>$start, 'te'=>$end]);
        $this['times'] = $re[0]['c'];

        return $this['times'] >= $maxTimes;
    }

    public function execute()
    {
        $sql = <<<SQL
INSERT INTO user_follow_teacher_log (userid, teacher_id) VALUES (:userid, :teacher_id)
SQL;
        Db::execute($sql, ['userid' => $this['uid'], 'teacher_id' => $this->params]);

        parent::execute();
    }

    public function tips()
    {
        return '您今天的关注任务已经完成！';
    }
}